module.exports = (app) => {
  const Comment = require("../models/Comment")
  const Message = require("../models/Message")

  const router = require("express").Router({
    // 合并父子路由路径参数
    mergeParams: true,
  })
  //资源路径
  app.use(
    "/admin/api/comment",
    async (req, res, next) => {
      next()
    },
    router
  )
  async function findPage(_id, page) {
    let commentCount = await Comment.countDocuments({ video: _id })
    let comment = await Comment.find({ video: _id })
      .sort("-createdAt")
      .limit(5)
      .skip((page - 1) * 5)
      .populate("author", ["nick", "headUrl"])
      .populate("reply.from", ["nick", "headUrl"])
      .populate("reply.to", ["nick", "headUrl"])
    return { comment, commentCount }
  }
  //评论页
  router.get("/page", async (req, res) => {
    // console.log(req.query)
    let { _id, page } = req.query
    let data = await findPage(_id, page)
    return res.send(data)
  })
  //回复
  router.post("/reply", async (req, res) => {
    let { _id, from, to, content, video, page, heSay } = req.body
    let comment = await Comment.findById(_id, "reply")
    let date = Date.now()
    comment.reply.push({ from, to, content, date })
    comment.save()
    await Message.insertMany({
      comment: _id,
      you: to,
      youSay: heSay,
      user: from,
      content,
      date,
    })
    let data = null
    //视频页则返回分页
    if (video) data = await findPage(video, page)
    return res.json(data)
  })
  //删除
  router.post("/delete", async (req, res) => {
    let { _id, reply, video, page } = req.body
    let comment
    //回复
    if (reply) {
      comment = await Comment.findById(_id)
      comment.reply = comment.reply.filter((value) => {
        return value._id + "" !== reply
      })
      comment.save()
    }
    //评论
    else {
      await Comment.findByIdAndDelete(_id)
    }
    let data = await findPage(video, page)
    return res.send(data)
  })

  //回复通知
  router.get("/message/:_id", async (req, res) => {
    let { _id } = req.params
    let result = await Message.find({ you: _id })
      .sort("-date")
      .populate("comment", ["content", "video"])
      .populate("you", ["nick", "headUrl"])
      .populate("user", ["nick", "headUrl"])
    res.send(result)
  })
}
